#include "json.h"

ipconfig read_server_config(const char*filename){
    ipconfig config = {"127.0.0.1","8989","3","0"};

    FILE*fp = fopen(filename,"r");
    fseek(fp,0,SEEK_END);
    long length = ftell(fp);
    fseek(fp,0,SEEK_SET);
    char*data = (char*)malloc(length+1);
    fread(data,1,length,fp);
    data[length] = '\0';
    fclose(fp);

    cJSON*json = cJSON_Parse(data);
    if(json){
       cJSON*server =  cJSON_GetObjectItemCaseSensitive(json,"server");
       if(server){
           cJSON*ip = cJSON_GetObjectItemCaseSensitive(server,"ip");
           cJSON*port = cJSON_GetObjectItemCaseSensitive(server,"port");
           cJSON*pthreadNum = cJSON_GetObjectItemCaseSensitive(server,"pthreadNum");
           cJSON*mysqlPassword= cJSON_GetObjectItemCaseSensitive(server,"mysqlPassword");

           if(cJSON_IsString(ip)&&(ip->valuestring!=NULL)){
                strncpy(config.ip,ip->valuestring,sizeof(config.ip)-1);
           }
           if(cJSON_IsString(port)&&(port->valuestring!=NULL)){
                strncpy(config.port,port->valuestring,sizeof(config.port)-1);
           }
           if(cJSON_IsString(pthreadNum)&&(pthreadNum->valuestring!=NULL)){
                strncpy(config.pthreadNum,pthreadNum->valuestring,sizeof(config.pthreadNum)-1);
           }
           if(cJSON_IsString(mysqlPassword)&&(mysqlPassword->valuestring!=NULL)){
                strncpy(config.mysqlPassward,mysqlPassword->valuestring,sizeof(config.mysqlPassward)-1);
           }

       }
    }
    cJSON_Delete(json);
    free(data);
    return config;
}

